import React, { useEffect, useRef, useMemo } from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import './index.<%= css %>';

const defaultTabHeight = 45;

interface ICovertIPhoneBottom {
  children: React.ReactNode;
  wrapperStyle?: any;
  onGetHeight?: (height: number) => void;
}

const CovertIPhoneBottom = (props: ICovertIPhoneBottom) => {
  const { onGetHeight } = props;

  const covertIphonexIdNum = useRef(0);

  const covertIphonexId = useMemo(() => `covertIphone-${covertIphonexIdNum.current + 1}`, [covertIphonexIdNum.current]);

  const getTabHeight = () => {
    Taro.nextTick(() => {
      // @ts-ignore
      const query = Taro.createSelectorQuery().in(Taro.getCurrentInstance().page);
      query
        .select(`#${covertIphonexId}`)
        .boundingClientRect((rect: any) => {
          const { height } = rect ?? {};
          onGetHeight?.(height || defaultTabHeight);
        })
        .exec();
    });
  };

  useEffect(() => {
    getTabHeight();
  }, [props.children]);

  return (
    <View id={covertIphonexId} className="covert-iphone-bottom-wrapper" style={props.wrapperStyle}>
      {props.children}
    </View>
  );
};

export default CovertIPhoneBottom;
